package one.three.twentyNine;

public class Queue<Item> {

	private static class Node<Item> {
		private Item item;
		private Node next;

		@Override
		public String toString() {
			return "[" + item + "]";
		}
	}

	private Node<Item> last;

	public void push(Item item) {
		if (last == null) {
			last = new Node<Item>();
			last.item = item;
			last.next = last;
		} else {
			Node<Item> n = new Node<Item>();
			n.item = item;
			n.next = last.next;
			last.next = n;	
		}
		/*
		if (last.next==last){
			Node<Item> f=last;
			this.last=new Node<Item>();
			last.item=item;
			last.next=f;
			f.next=last;
		}else {
			Node<Item> n = new Node<Item>();
			n.item = item;
			n.next = last.next;
			last.next = n;	
		}
		*/
		/*
		 Node<Item> n = new Node<Item>();
			n.item = item;
			n.next = last.next;
			last.next = n;
		 */
	}

	public Item pop() {
		if (last == null) {
			return null;
		} else {
			Item item = last.item;
			if (last.next == null) {
				last = null;
			} else {
				Node<Item> f = last.next;
				while (f.next != last) {
					f = f.next;
				}
				f.next = last.next;
			}
			return item;
		}

	}

	@Override
	public String toString() {
		String r = "[]";
		if (last == null) {

		} else if (last.next == last) {
			r = "[" + last.item.toString() + "]";
		} else {
			StringBuilder sb = new StringBuilder();
			Node<Item> f = last.next;
			while (f != last) {
				sb.append("[" + f.item + "]");
				f = f.next;
			}
			sb.append("[" + last.item + "]");
			r = sb.toString();
		}

		return r;
	}

	public static void main(String[] args) {
		Queue<String> q = new Queue<String>();
		for (int i = 0; i < 3; i++) {
			q.push(i + "");
			System.out.println(q);
		}

		//System.out.println(q);
		
		/*
		StringBuilder sb=new StringBuilder();
		sb.append("A__");
		sb.append("b--");
		System.out.println(sb.toString());
		*/
	}

}
